import StudentSearch from './StudentSearch'
import StucentTable from './StucentTable'
import Loading from './Loading'
import Pager from './Pager'
import { connect, Provider, connectAdvanced } from 'react-redux'
import store from '../store'
import { change } from '../store/actions/student/searchCondition'
import { fetchStudents } from '../store/actions/student/searchResult'
import { useEffect } from 'react'
// @ts-ignore
const SearchBar = connect(state => ({ dufaultValue: state.student.condition }), dispatch => ({
    onSearch: newCondition => {
        // 设置查询条件
        dispatch(change({ ...newCondition, page: 1 }))
        // 获取数据
        dispatch(fetchStudents())
    }
}))(StudentSearch)

// @ts-ignore
const Table = connect(state => ({ stus: state.student.result.datas }))(StucentTable)

const PagerComp = connect(state => {
    // @ts-ignore
    const { result: { total }, condition: { page, limit } } = state.student
    return { total, current: page, limit }
}, dispatch => ({
    onPageChange: (page) => {
        dispatch(change({ page }))
        dispatch(fetchStudents())
    }
}))(Pager)

// @ts-ignore
const LoadingTemp = connect(state => ({ show: state.student.result.isLoading }))(Loading)


function selectorFactory(dispatch) {
    return (state, ownProps) => {
        // state:仓库数据 ownProps:组件额外属性 
        const { result: { total }, condition: { page, limit } } = state.student
        return {
            total, current: page, limit,
            onPageChange: (page) => {
                dispatch(change({ page }))
                dispatch(fetchStudents())
            }
        }
    }
}

const AdvancedPager = connectAdvanced(selectorFactory)(Pager)

export function StudentComp() {
    useEffect(() => store.dispatch(fetchStudents()), [])
    return <Provider store={store}>
        <SearchBar />
        <Table />
        <PagerComp />
        <AdvancedPager a="x" />
        <LoadingTemp />
    </Provider>
}